import New from '@/utils/new'
import { Message } from 'element-ui'

export default class LayerManager {
  constructor(viewer) {
    this._viewer = viewer
    // this._layers = new Map()
    this._layers = []
    // this._loadingLayers = []
    this._eventListener = {
      add: [],
      del: []
    }
  }

  set layers(value) {
    this._layers = value
  }

  get originLayers() {
    return this._layers
  }

  get layers() {
    // return [...this._layers.values()]
    return this._layers
  }

  get clip() {
    const tilesetList = this.layers.map(
      (item) => item.layer
    )
    let positions = []
    let regions = []
    let handlerPolygon = null
    let handlerBox = null
    let boxEntity = null
    let editorBox = null
    let clipMode = ''
    let currentClipType = ''
    return {
      clear: () => {
        if (handlerPolygon) {
          handlerPolygon.clear()
        }
        for (let i = 0; i < tilesetList.length; i++) {
          for (let j = 0; j < tilesetList[i].length; j++) {
            if (tilesetList[i][j].clearCustomClipBox) {
              tilesetList[i][j].clearCustomClipBox()
            }
            if (tilesetList[i][j].clearModifyRegions) {
              tilesetList[i][j].clearModifyRegions()
            }
          }
        }
        if (editorBox) {
          editorBox.deactivate()
        }
        this._viewer.entities.removeAll()
        if (handlerBox) {
          handlerBox.clear()
          handlerBox.deactivate()
        }
      },
      setClipMode: (mode) => {
        clipMode = mode
        if (currentClipType === 'face') {
          tilesetList.forEach((clipTileset) => {
            if (clipTileset.setModifyRegions) {
              clipTileset.setModifyRegions(
                regions,
                clipMode === 'out'
                  ? Cesium.ModifyRegionMode.CLIP_OUTSIDE
                  : Cesium.ModifyRegionMode.CLIP_INSIDE
              )
            } else if (clipTileset instanceof Array) {
              clipTileset.forEach((tileset) => {
                tileset.setModifyRegions &&
                  tileset.setModifyRegions(
                    regions,
                    clipMode === 'out'
                      ? Cesium.ModifyRegionMode.CLIP_OUTSIDE
                      : Cesium.ModifyRegionMode.CLIP_INSIDE
                  )
              })
            }
          })
        }
      },
      // 平面裁剪
      face: () => {
        currentClipType = 'face'
        if (handlerBox) {
          for (
            let i = 0, j = tilesetList.length;
            i < j;
            i++
          ) {
            if (tilesetList[i].clearModifyRegions) {
              tilesetList[i].clearModifyRegions()
            } else if (tilesetList[i] instanceof Array) {
              tilesetList[0].forEach((tileset) => {
                tileset.clearModifyRegions &&
                  tileset.clearModifyRegions()
              })
            }
          }
          if (editorBox) {
            editorBox.deactivate()
          }
          this._viewer.entities.removeAll()
          handlerBox.clear()
          handlerBox.deactivate()
        }
        if (!handlerPolygon) {
          handlerPolygon = new Cesium.DrawHandler(
            this._viewer,
            Cesium.DrawMode.Polygon,
            0
          )
          handlerPolygon.activeEvt.addEventListener(
            (isActive) => {
              if (isActive === true) {
                this._viewer.enableCursorStyle = false
                this._viewer._element.style.cursor = ''
              } else {
                this._viewer.enableCursorStyle = true
              }
            }
          )
          handlerPolygon.drawEvt.addEventListener(
            (result) => {
              handlerPolygon.polygon.show = false
              handlerPolygon.polyline.show = false
              positions = []
              for (const pt of result.object.positions) {
                const cartographic =
                  Cesium.Cartographic.fromCartesian(pt)
                const longitude = Cesium.Math.toDegrees(
                  cartographic.longitude
                )
                const latitude = Cesium.Math.toDegrees(
                  cartographic.latitude
                )
                const height = cartographic.height
                positions.push(longitude, latitude, height)
              }
              regions = []
              regions.push(positions)
              tilesetList.forEach((clipTileset) => {
                if (clipTileset.setModifyRegions) {
                  clipTileset.setModifyRegions(
                    regions,
                    clipMode === 'out'
                      ? Cesium.ModifyRegionMode.CLIP_OUTSIDE
                      : Cesium.ModifyRegionMode.CLIP_INSIDE
                  )
                } else if (clipTileset instanceof Array) {
                  clipTileset.forEach((tileset) => {
                    tileset.setModifyRegions &&
                      tileset.setModifyRegions(
                        regions,
                        clipMode === 'out'
                          ? Cesium.ModifyRegionMode
                              .CLIP_OUTSIDE
                          : Cesium.ModifyRegionMode
                              .CLIP_INSIDE
                      )
                  })
                }
              })
            }
          )
        }
        handlerPolygon.activate()
      },
      // 盒子裁剪
      box: () => {
        currentClipType = 'box'
        if (handlerPolygon) {
          handlerPolygon.deactivate()
        }
        if (!handlerBox) {
          setAllLayersClipColor()
          handlerBox = new Cesium.DrawHandler(
            this._viewer,
            Cesium.DrawMode.Box
          )
          handlerBox.drawEvt.addEventListener((e) => {
            boxEntity = e.object
            const newDim =
              boxEntity.box.dimensions.getValue()
            const position = boxEntity.position.getValue(0)
            const boxOption = {
              dimensions: newDim,
              position: position,
              clipMode:
                clipMode === 'out'
                  ? 'clip_behind_any_plane'
                  : 'clip_behind_all_plane',
              heading: 0
            }

            // box编辑
            editorBox = new Cesium.BoxEditor(
              this._viewer,
              boxEntity
            )

            editorBox.editEvt.addEventListener((e) => {
              boxEntity.box.dimensions = e.dimensions
              boxEntity.position = e.position
              boxEntity.orientation = e.orientation

              setClipBox()
            })
            editorBox.distanceDisplayCondition =
              new Cesium.DistanceDisplayCondition(0, 950)
            editorBox.activate()
            setAllLayersClipOptions(boxOption)
            // tooltip.setVisible(false)
            handlerBox.clear()
            handlerBox.deactivate()
          })
        }
        handlerBox.activate()

        function setAllLayersClipColor() {
          for (
            let i = 0, j = tilesetList.length;
            i < j;
            i++
          ) {
            if (tilesetList[i].clipLineColor) {
              tilesetList[i].clipLineColor =
                new Cesium.Color(1, 1, 1, 0)
            } else if (tilesetList[i] instanceof Array) {
              tilesetList[i].forEach((tileset) => {
                if (tileset.clipLineColor) {
                  tileset.clipLineColor = new Cesium.Color(
                    1,
                    1,
                    1,
                    0
                  )
                }
              })
            }
          }
        }

        function setAllLayersClipOptions(boxOptions) {
          for (
            let i = 0, j = tilesetList.length;
            i < j;
            i++
          ) {
            if (tilesetList[i].setCustomClipBox) {
              tilesetList[i].setCustomClipBox(boxOptions)
            } else if (tilesetList[i] instanceof Array) {
              tilesetList[i].forEach((tileset) => {
                tileset.setCustomClipBox &&
                  tileset.setCustomClipBox(boxOptions)
              })
            }
          }
        }

        function setClipBox() {
          if (typeof boxEntity === 'undefined') {
            return
          }
          const newDim = boxEntity.box.dimensions.getValue()
          const position = boxEntity.position.getValue(0)

          let heading = 0
          if (
            typeof boxEntity.orientation !== 'undefined'
          ) {
            const rotationM3 =
              Cesium.Matrix3.fromQuaternion(
                boxEntity.orientation._value,
                new Cesium.Matrix3()
              )
            const localFrame =
              Cesium.Matrix4.fromRotationTranslation(
                rotationM3,
                Cesium.Cartesian3.ZERO,
                new Cesium.Matrix4()
              )
            const inverse = Cesium.Matrix4.inverse(
              Cesium.Transforms.eastNorthUpToFixedFrame(
                position
              ),
              new Cesium.Matrix4()
            )
            const hprm = Cesium.Matrix4.multiply(
              inverse,
              localFrame,
              new Cesium.Matrix4()
            )
            const rotation = Cesium.Matrix4.getMatrix3(
              hprm,
              new Cesium.Matrix3()
            )
            const hpr =
              Cesium.HeadingPitchRoll.fromQuaternion(
                Cesium.Quaternion.fromRotationMatrix(
                  rotation
                )
              )
            heading = hpr.heading
          }

          const boxOptions = {
            dimensions: newDim,
            position: position,
            clipMode:
              clipMode === 'out'
                ? 'clip_behind_any_plane'
                : 'clip_behind_all_plane',
            heading: heading
          }
          for (
            let i = 0, j = tilesetList.length;
            i < j;
            i++
          ) {
            if (tilesetList[i].setCustomClipBox) {
              tilesetList[i].setCustomClipBox(boxOptions)
            } else if (tilesetList[i] instanceof Array) {
              tilesetList[i].forEach((tileset) => {
                tileset.setCustomClipBox &&
                  tileset.setCustomClipBox(boxOptions)
              })
            }
          }
        }
      }
      // setClipBox: () => {
      //   if (typeof boxEntity === 'undefined') {
      //     return
      //   }
      //   const newDim = boxEntity.box.dimensions.getValue()
      //   const position = boxEntity.position.getValue(0)
      //
      //   let heading = 0
      //   if (typeof boxEntity.orientation !== 'undefined') {
      //     const rotationM3 = Cesium.Matrix3.fromQuaternion(
      //       boxEntity.orientation._value,
      //       new Cesium.Matrix3()
      //     )
      //     const localFrame =
      //       Cesium.Matrix4.fromRotationTranslation(
      //         rotationM3,
      //         Cesium.Cartesian3.ZERO,
      //         new Cesium.Matrix4()
      //       )
      //     const inverse = Cesium.Matrix4.inverse(
      //       Cesium.Transforms.eastNorthUpToFixedFrame(
      //         position
      //       ),
      //       new Cesium.Matrix4()
      //     )
      //     const hprm = Cesium.Matrix4.multiply(
      //       inverse,
      //       localFrame,
      //       new Cesium.Matrix4()
      //     )
      //     const rotation = Cesium.Matrix4.getMatrix3(
      //       hprm,
      //       new Cesium.Matrix3()
      //     )
      //     const hpr =
      //       Cesium.HeadingPitchRoll.fromQuaternion(
      //         Cesium.Quaternion.fromRotationMatrix(rotation)
      //       )
      //     heading = hpr.heading
      //   }
      //
      //   const boxOptions = {
      //     dimensions: newDim,
      //     position: position,
      //     clipMode:
      //       clipMode === 'out'
      //         ? 'clip_behind_any_plane'
      //         : 'clip_behind_all_plane',
      //     heading: heading
      //   }
      //   for (
      //     let i = 0, j = tilesetList.length;
      //     i < j;
      //     i++
      //   ) {
      //     if (tilesetList[i].setCustomClipBox) {
      //       tilesetList[i].setCustomClipBox(boxOptions)
      //     } else if (tilesetList[i] instanceof Array) {
      //       tilesetList[i].forEach((tileset) => {
      //         tileset.setCustomClipBox &&
      //           tileset.setCustomClipBox(boxOptions)
      //       })
      //     }
      //   }
      // }
    }
  }

  get viewer() {
    return this._viewer
  }

  on(type, callback) {
    if (!this._eventListener[type]) {
      console.error('不支持类型', type)
    }
    this._eventListener[type].push(callback)
  }

  off(type, callback) {
    if (!this._eventListener[type]) {
      console.error('不支持类型', type)
    }
    const index = this._eventListener[type].findIndex(
      (item) => item === callback
    )
    if (index > -1) {
      this._eventListener[type].splice(index, 1)
    }
  }

  fire(type, params) {
    this._eventListener[type].forEach((fn) => {
      fn(params)
    })
  }

  add(params) {
    const {
      pkid,
      serviceType,
      sourceName,
      serviceUrl,
      signService,
      dataService,
      from,
      specialType,
      specialWord,
      currentDataIndex,
      dataList
    } = params
    // if (this._loadingLayers.includes(pkid)) return
    if (this._layers.find((item) => item.id === pkid)) {
      return
    }
    const memoryRemain =
      window.cesiumMaxMemory -
      window.performance.memory.usedJSHeapSize / 1024 / 1024
    if (memoryRemain <= 100) {
      Message.warning(
        '内存不足，为了保持系统正常运行，建议关闭部分图层'
      )
    }
    // const { id, type } = params
    // if (this._loadingLayers.includes(id)) return
    // if (this._layers.has(id)) return
    // console.log(params, 'typeNames')
    const passParams = {
      id: pkid,
      title: sourceName,
      name: sourceName,
      signService: signService,
      dataService: dataService,
      from: from,
      specialType: specialType,
      specialWord: specialWord,
      serviceType: serviceType,
      currentDataIndex: currentDataIndex,
      dataList: dataList
    }
    switch (serviceType) {
      case '2':
        this.addGeojson(params)
        break
      // 矢量服务
      case '23':
        passParams.type = 'mvt'
        passParams.url = serviceUrl
        this.addMvt(passParams)
        break
      // rest服务
      case '26':
        passParams.type = 'imagery'
        if (serviceUrl.lastIndexOf('leaflet') !== -1) {
          passParams.url = serviceUrl.substring(
            0,
            serviceUrl.lastIndexOf('leaflet') - 1
          )
        } else {
          passParams.url = serviceUrl
        }
        this.addImagery(passParams)
        break
      case '27':
        // realspace服务
        passParams.type = 'layer'
        if (serviceUrl[0] === '[') {
          const bimList = JSON.parse(serviceUrl)
          const first = bimList.find(
            (item) => item.serviceUrl
          )
          if (first) {
            passParams.bimCode = first.bimCode
            // 两种url格式
            // 1-配置到到realspace层级: http://chengyu.caupdwest.com:7000/iserver/services/3D-KeJiChengShuJuKu-2/rest/realspace
            // 2-配置到具体场景: http://chengyu.caupdwest.com:7000/iserver/services/3D-KeJiChengShuJuKu-2/rest/realspace/scenes/城市设计模型场景
            if (
              first.serviceUrl.indexOf(
                '/realspace/datas/'
              ) !== -1
            ) {
              passParams.url = first.serviceUrl
              passParams.dataService = first.dataService
              this.addLayerByScp(passParams)
            } else if (
              first.serviceUrl.indexOf(
                '/realspace/scenes/'
              ) === -1
            ) {
              passParams.url = first.serviceUrl
              passParams.name = undefined
              passParams.dataService = first.dataService
              console.log(
                '第1种情况',
                passParams.url,
                passParams.name
              )
              this.addLayer(passParams)
            } else {
              passParams.url = first.serviceUrl.substring(
                0,
                first.serviceUrl.indexOf('/scenes')
              )
              passParams.name = decodeURI(
                first.serviceUrl.substring(
                  first.serviceUrl.indexOf('/scenes/') +
                    '/scenes/'.length
                )
              )
              passParams.dataService = first.dataService
              console.log(
                '第2种情况',
                passParams.url,
                passParams.name
              )
              this.addLayer(passParams)
            }
          }
        } else {
          // 两种url格式
          // 1-配置到到realspace层级: http://chengyu.caupdwest.com:7000/iserver/services/3D-KeJiChengShuJuKu-2/rest/realspace
          // 2-配置到具体场景: http://chengyu.caupdwest.com:7000/iserver/services/3D-KeJiChengShuJuKu-2/rest/realspace/scenes/城市设计模型场景
          if (
            serviceUrl.indexOf('/realspace/datas/') !== -1
          ) {
            passParams.url = serviceUrl
            if (
              passParams.dataList[
                passParams.currentDataIndex
              ].resourceServiceDataInfoList.length
            ) {
              passParams.dataService =
                passParams.dataList[
                  passParams.currentDataIndex
                ].resourceServiceDataInfoList[0].serviceDataUrl
            } else {
              passParams.dataService = null
            }
            this.addLayerByScp(passParams)
          } else if (
            serviceUrl.indexOf('/realspace/scenes/') === -1
          ) {
            passParams.url = serviceUrl
            passParams.name = undefined
            console.log(
              '第1种情况',
              passParams.url,
              passParams.name
            )
            if (
              passParams.dataList[
                passParams.currentDataIndex
              ].resourceServiceDataInfoList.length
            ) {
              passParams.dataService =
                passParams.dataList[
                  passParams.currentDataIndex
                ].resourceServiceDataInfoList[0].serviceDataUrl
            } else {
              passParams.dataService = null
            }
            this.addLayer(passParams)
          } else {
            passParams.url = serviceUrl.substring(
              0,
              serviceUrl.indexOf('/scenes')
            )
            passParams.name = decodeURI(
              serviceUrl.substring(
                serviceUrl.indexOf('/scenes/') +
                  '/scenes/'.length
              )
            )
            console.log(
              '第2种情况',
              passParams.url,
              passParams.name
            )
            if (
              passParams.dataList[
                passParams.currentDataIndex
              ].resourceServiceDataInfoList.length
            ) {
              passParams.dataService =
                passParams.dataList[
                  passParams.currentDataIndex
                ].resourceServiceDataInfoList[0].serviceDataUrl
            } else {
              passParams.dataService = null
            }
            this.addLayer(passParams)
          }
        }
        break
      case 'tileset':
        this.addTileset(params)
        break
      default:
        break
    }
  }

  async addAsync(params) {
    return new Promise((resolve) => {
      const {
        pkid,
        serviceType,
        sourceName,
        serviceUrl,
        signService,
        dataService,
        from,
        specialType,
        specialWord,
        currentDataIndex,
        dataList
      } = params
      if (this._layers.find((item) => item.id === pkid)) {
        console.error('服务已存在')
        resolve(false)
      }
      const memoryRemain =
        window.cesiumMaxMemory -
        window.performance.memory.usedJSHeapSize /
          1024 /
          1024
      if (memoryRemain <= 100) {
        Message.warning(
          '内存不足，为了保持系统正常运行，建议关闭部分图层'
        )
      }
      const passParams = {
        id: pkid,
        title: sourceName,
        name: sourceName,
        signService: signService,
        dataService: dataService,
        from: from,
        specialType: specialType,
        specialWord: specialWord,
        serviceType: serviceType,
        currentDataIndex: currentDataIndex,
        dataList: dataList
      }
      let find
      let promise
      switch (serviceType) {
        case '2':
          // this.addGeojson(params)
          const geojson = Cesium.GeoJsonDataSource.load(
            serviceUrl,
            { clampToGround: true }
          )
          Cesium.when(geojson, (dataSource) => {
            if (dataSource) {
              this._viewer.dataSources.add(dataSource)
              // this._viewer.flyTo(dataSource)
              this.set({
                pkid,
                title,
                serviceType,
                layer: dataSource,
                from
              })
              resolve(true)
            } else {
              resolve(false)
            }
          })
          break
        // 矢量服务
        case '23':
          passParams.type = 'mvt'
          passParams.url = serviceUrl
          // this.addMvt(passParams)
          this.set({
            id: passParams.id,
            title: passParams.title,
            name: passParams.name,
            type: passParams.type,
            layer: null,
            from: passParams.from,
            serviceUrl: passParams.url,
            signService: passParams.signService,
            dataService: passParams.dataService,
            serviceType: passParams.serviceType,
            currentDataIndex: passParams.currentDataIndex,
            dataList: passParams.dataList
          })

          // 加载mvt
          const mvt = this._viewer.scene.addVectorTilesMap({
            url: passParams.url,
            // canvasWidth: 512,
            name: passParams.name,
            viewer: this._viewer
          })

          find = this._layers.find(
            (item) => item.id === passParams.id
          )
          if (find) {
            find.layer = mvt

            this.fire('add', find)

            New.$emit('showDataList', find)
          }

          if (
            passParams.url.indexOf(
              'map-mvt-B0106GongGongFuWuSheShi/restjsr/v1/vectortile/maps/B0106_%E5%85%AC%E5%85%B1%E6%9C%8D%E5%8A%A1%E8%AE%BE%E6%96%BD%E6%96%B0'
            ) !== -1
          ) {
            mvt.isOverlapDisplayed = true
          }
          // mvt.lineAntialiasing = true
          const mvpReadyPromise = mvt.readyPromise
          Cesium.when(mvpReadyPromise, (data) => {
            if (data) {
              // console.log('添加成功')
              // const bounds = mvt.rectangle
              // this._viewer.scene.camera.setView({
              //   destination: Cesium.Cartesian3.fromRadians(
              //     (bounds.east + bounds.west) * 0.5,
              //     (bounds.north + bounds.south) * 0.5,
              //     10000
              //   )
              // })
              // console.log('加载mvt完成')
              resolve(true)
            } else {
              console.error('添加失败')
              resolve(false)
            }
          })
          break
        // rest服务
        case '26':
          passParams.type = 'imagery'
          if (serviceUrl.lastIndexOf('leaflet') !== -1) {
            passParams.url = serviceUrl.substring(
              0,
              serviceUrl.lastIndexOf('leaflet') - 1
            )
          } else {
            passParams.url = serviceUrl
          }
          // this.addImagery(passParams)
          this.set({
            id: passParams.id,
            title: passParams.title,
            name: passParams.name,
            type: passParams.type,
            layer: null,
            from: passParams.from,
            serviceUrl: passParams.url,
            signService: passParams.signService,
            dataService: passParams.dataService,
            specialType: passParams.specialType,
            specialWord: passParams.specialWord,
            serviceType: passParams.serviceType,
            currentDataIndex: passParams.currentDataIndex,
            dataList: passParams.dataList
          })

          const provider =
            new Cesium.SuperMapImageryProvider({
              url: passParams.url
            })
          const imagery =
            this._viewer.scene.imageryLayers.addImageryProvider(
              provider
            )

          find = this._layers.find(
            (item) => item.id === passParams.id
          )
          if (find) {
            find.layer = imagery

            this.fire('add', find)

            New.$emit('showDataList', find)

            // console.log('加载rest完成')
            resolve(true)
          } else {
            resolve(false)
          }
          break
        // realspace服务
        case '27':
          passParams.type = 'layer'
          if (serviceUrl[0] === '[') {
            const bimList = JSON.parse(serviceUrl)
            const first = bimList.find(
              (item) => item.serviceUrl
            )
            if (first) {
              passParams.bimCode = first.bimCode
              if (
                first.serviceUrl.indexOf(
                  '/realspace/datas/'
                ) !== -1
              ) {
                passParams.url = first.serviceUrl
                passParams.dataService = first.dataService
                // this.addLayerByScp(passParams)
                this.set({
                  id: passParams.id,
                  title: passParams.title,
                  name: [],
                  type: passParams.type,
                  layer: [],
                  from: passParams.from,
                  serviceUrl: passParams.url,
                  signService: passParams.signService,
                  dataService: passParams.dataService,
                  serviceType: '27',
                  currentDataIndex:
                    passParams.currentDataIndex,
                  dataList: passParams.dataList
                })
                promise =
                  this._viewer.scene.addS3MTilesLayerByScp(
                    passParams.url + '/config',
                    {
                      autoSetView: false,
                      name: passParams.name
                    }
                  )
                Cesium.when(promise, (layer) => {
                  if (layer) {
                    layer.clearMemoryImmediately = true
                    layer.residentRootTile = false
                    layer.isOverlapDisplayed = false
                    layer.orderIndependentTranslucency = true
                    // layer.indexedDB &&
                    //   (layer.indexedDBSetting.isGeoTilesRootNodeSave = true)
                    layer.style3D &&
                      (layer.style3D.altitudeMode =
                        Cesium.HeightReference.CLAMP_TO_GROUND)
                    // 设置查询参数，用于BIM属性查询
                    if (passParams.dataService) {
                      if (
                        passParams.dataService.lastIndexOf(
                          '/datasets/'
                        ) !== -1
                      ) {
                        layer.setQueryParameter({
                          url: passParams.dataService.substring(
                            0,
                            passParams.dataService.lastIndexOf(
                              '/datasources/'
                            )
                          ),
                          dataSourceName:
                            passParams.dataService.lastIndexOf(
                              '/datasets/'
                            ) !== -1
                              ? passParams.dataService.substring(
                                  passParams.dataService.lastIndexOf(
                                    '/datasources/'
                                  ) +
                                    '/datasources/'.length,
                                  passParams.dataService.lastIndexOf(
                                    '/datasets/'
                                  )
                                )
                              : passParams.dataService.substring(
                                  passParams.dataService.lastIndexOf(
                                    '/datasources/'
                                  ) + '/datasources/'.length
                                ),
                          dataSetName:
                            passParams.dataService.substring(
                              passParams.dataService.lastIndexOf(
                                '/datasets/'
                              ) + '/datasets/'.length
                            ),
                          hasGeometry: false
                        })
                      } else {
                        layer.setQueryParameter({
                          url: passParams.dataService.substring(
                            0,
                            passParams.dataService.lastIndexOf(
                              '/datasources/'
                            )
                          ),
                          dataSourceName:
                            passParams.dataService.lastIndexOf(
                              '/datasets/'
                            ) !== -1
                              ? passParams.dataService.substring(
                                  passParams.dataService.lastIndexOf(
                                    '/datasources/'
                                  ) +
                                    '/datasources/'.length,
                                  passParams.dataService.lastIndexOf(
                                    '/datasets/'
                                  )
                                )
                              : passParams.dataService.substring(
                                  passParams.dataService.lastIndexOf(
                                    '/datasources/'
                                  ) + '/datasources/'.length
                                ),
                          hasGeometry: false
                        })
                      }
                    }
                    find = this._layers.find(
                      (item) => item.id === passParams.id
                    )
                    if (find) {
                      find.name = [passParams.name]
                      find.layer = [layer]

                      this.fire('add', find)

                      New.$emit('showDataList', find)
                    }
                    // console.log('加载realspace完成')
                    resolve(true)
                  } else {
                    console.error('添加失败')
                    resolve(false)
                  }
                })
              } else if (
                first.serviceUrl.indexOf(
                  '/realspace/scenes/'
                ) === -1
              ) {
                passParams.url = first.serviceUrl
                passParams.name = undefined
                passParams.dataService = first.dataService
                // this.addLayer(passParams)
                this.set({
                  id: passParams.id,
                  title: passParams.title,
                  name: [],
                  type: passParams.type,
                  layer: [],
                  from: passParams.from,
                  serviceUrl: passParams.url,
                  signService: passParams.signService,
                  dataService: passParams.dataService,
                  bimCode: passParams.bimCode,
                  serviceType: '27',
                  currentDataIndex:
                    passParams.currentDataIndex,
                  dataList: passParams.dataList
                })

                promise = this._viewer.scene.open(
                  passParams.url,
                  passParams.name,
                  {
                    autoSetView: false
                  }
                )
                Cesium.when(promise, (layers) => {
                  if (layers) {
                    // 设置查询参数，用于BIM属性查询
                    layers.forEach((layer) => {
                      // 每个子图层的透明度可能不一致，需要保存子图层的原始透明度，用于在图层工具中调整透明度时分别计算
                      if (layer.alpha !== undefined) {
                        layer.originAlpha = layer.alpha
                      } else if (layer.style3D) {
                        layer.originFillForeColorAlpha =
                          layer.style3D.fillForeColor.alpha
                      }

                      layer.clearMemoryImmediately = true
                      layer.residentRootTile = false
                      layer.isOverlapDisplayed = false
                      layer.orderIndependentTranslucency = true
                      layer.style3D &&
                        (layer.style3D.altitudeMode =
                          Cesium.HeightReference.CLAMP_TO_GROUND)
                      if (passParams.dataService) {
                        if (
                          passParams.dataService.lastIndexOf(
                            '/datasets/'
                          ) !== -1
                        ) {
                          layer.setQueryParameter({
                            url: passParams.dataService.substring(
                              0,
                              passParams.dataService.lastIndexOf(
                                '/datasources/'
                              )
                            ),
                            dataSourceName:
                              passParams.dataService.lastIndexOf(
                                '/datasets/'
                              ) !== -1
                                ? passParams.dataService.substring(
                                    passParams.dataService.lastIndexOf(
                                      '/datasources/'
                                    ) +
                                      '/datasources/'
                                        .length,
                                    passParams.dataService.lastIndexOf(
                                      '/datasets/'
                                    )
                                  )
                                : passParams.dataService.substring(
                                    passParams.dataService.lastIndexOf(
                                      '/datasources/'
                                    ) +
                                      '/datasources/'.length
                                  ),
                            dataSetName:
                              passParams.dataService.substring(
                                passParams.dataService.lastIndexOf(
                                  '/datasets/'
                                ) + '/datasets/'.length
                              ),
                            hasGeometry: false
                          })
                        } else {
                          layer.setQueryParameter({
                            url: passParams.dataService.substring(
                              0,
                              passParams.dataService.lastIndexOf(
                                '/datasources/'
                              )
                            ),
                            dataSourceName:
                              passParams.dataService.lastIndexOf(
                                '/datasets/'
                              ) !== -1
                                ? passParams.dataService.substring(
                                    passParams.dataService.lastIndexOf(
                                      '/datasources/'
                                    ) +
                                      '/datasources/'
                                        .length,
                                    passParams.dataService.lastIndexOf(
                                      '/datasets/'
                                    )
                                  )
                                : passParams.dataService.substring(
                                    passParams.dataService.lastIndexOf(
                                      '/datasources/'
                                    ) +
                                      '/datasources/'.length
                                  ),
                            hasGeometry: false
                          })
                        }
                      }
                    })
                    const realName = layers.map(
                      (item) => item.name
                    )
                    const find = this._layers.find(
                      (item) => item.id === passParams.id
                    )
                    if (find) {
                      find.name = realName
                      find.layer = layers

                      this.fire('add', find)

                      New.$emit('showDataList', find)
                    }
                    // console.log('加载realspace完成')
                    resolve(true)
                  } else {
                    console.error('添加失败')
                    resolve(false)
                  }
                })
              } else {
                passParams.url = first.serviceUrl.substring(
                  0,
                  first.serviceUrl.indexOf('/scenes')
                )
                passParams.name = decodeURI(
                  first.serviceUrl.substring(
                    first.serviceUrl.indexOf('/scenes/') +
                      '/scenes/'.length
                  )
                )
                passParams.dataService = first.dataService
                // this.addLayer(passParams)
                this.set({
                  id: passParams.id,
                  title: passParams.title,
                  name: [],
                  type: passParams.type,
                  layer: [],
                  from,
                  serviceUrl: passParams.url,
                  signService: passParams.signService,
                  dataService: passParams.dataService,
                  bimCode: passParams.bimCode,
                  serviceType: '27',
                  currentDataIndex:
                    passParams.currentDataIndex,
                  dataList: passParams.dataList
                })

                promise = this._viewer.scene.open(
                  passParams.url,
                  passParams.name,
                  {
                    autoSetView: false
                  }
                )
                Cesium.when(promise, (layers) => {
                  if (layers) {
                    // 设置查询参数，用于BIM属性查询
                    layers.forEach((layer) => {
                      // 每个子图层的透明度可能不一致，需要保存子图层的原始透明度，用于在图层工具中调整透明度时分别计算
                      if (layer.alpha !== undefined) {
                        layer.originAlpha = layer.alpha
                      } else if (layer.style3D) {
                        layer.originFillForeColorAlpha =
                          layer.style3D.fillForeColor.alpha
                      }

                      layer.clearMemoryImmediately = true
                      layer.residentRootTile = false
                      layer.isOverlapDisplayed = false
                      layer.orderIndependentTranslucency = true
                      layer.style3D &&
                        (layer.style3D.altitudeMode =
                          Cesium.HeightReference.CLAMP_TO_GROUND)
                      if (passParams.dataService) {
                        if (
                          passParams.dataService.lastIndexOf(
                            '/datasets/'
                          ) !== -1
                        ) {
                          layer.setQueryParameter({
                            url: passParams.dataService.substring(
                              0,
                              passParams.dataService.lastIndexOf(
                                '/datasources/'
                              )
                            ),
                            dataSourceName:
                              passParams.dataService.lastIndexOf(
                                '/datasets/'
                              ) !== -1
                                ? passParams.dataService.substring(
                                    passParams.dataService.lastIndexOf(
                                      '/datasources/'
                                    ) +
                                      '/datasources/'
                                        .length,
                                    passParams.dataService.lastIndexOf(
                                      '/datasets/'
                                    )
                                  )
                                : passParams.dataService.substring(
                                    passParams.dataService.lastIndexOf(
                                      '/datasources/'
                                    ) +
                                      '/datasources/'.length
                                  ),
                            dataSetName:
                              passParams.dataService.substring(
                                passParams.dataService.lastIndexOf(
                                  '/datasets/'
                                ) + '/datasets/'.length
                              ),
                            hasGeometry: false
                          })
                        } else {
                          layer.setQueryParameter({
                            url: passParams.dataService.substring(
                              0,
                              passParams.dataService.lastIndexOf(
                                '/datasources/'
                              )
                            ),
                            dataSourceName:
                              passParams.dataService.lastIndexOf(
                                '/datasets/'
                              ) !== -1
                                ? passParams.dataService.substring(
                                    passParams.dataService.lastIndexOf(
                                      '/datasources/'
                                    ) +
                                      '/datasources/'
                                        .length,
                                    passParams.dataService.lastIndexOf(
                                      '/datasets/'
                                    )
                                  )
                                : passParams.dataService.substring(
                                    passParams.dataService.lastIndexOf(
                                      '/datasources/'
                                    ) +
                                      '/datasources/'.length
                                  ),
                            hasGeometry: false
                          })
                        }
                      }
                    })
                    const realName = layers.map(
                      (item) => item.name
                    )
                    const find = this._layers.find(
                      (item) => item.id === passParams.id
                    )
                    if (find) {
                      find.name = realName
                      find.layer = layers

                      this.fire('add', find)

                      New.$emit('showDataList', find)
                    }
                    // console.log('加载realspace完成')
                    resolve(true)
                  } else {
                    console.error('添加失败')
                    resolve(false)
                  }
                })
              }
            }
          } else {
            if (
              serviceUrl.indexOf('/realspace/datas/') !== -1
            ) {
              passParams.url = serviceUrl
              if (
                passParams.dataList[
                  passParams.currentDataIndex
                ].resourceServiceDataInfoList.length
              ) {
                passParams.dataService =
                  passParams.dataList[
                    passParams.currentDataIndex
                  ].resourceServiceDataInfoList[0].serviceDataUrl
              } else {
                passParams.dataService = null
              }
              // this.addLayerByScp(passParams)
              this.set({
                id: passParams.id,
                title: passParams.title,
                name: [],
                type: passParams.type,
                layer: [],
                from: passParams.from,
                serviceUrl: passParams.url,
                signService: passParams.signService,
                dataService: passParams.dataService,
                serviceType: '27',
                currentDataIndex:
                  passParams.currentDataIndex,
                dataList: passParams.dataList
              })
              promise =
                this._viewer.scene.addS3MTilesLayerByScp(
                  passParams.url + '/config',
                  {
                    autoSetView: false,
                    name: passParams.name
                  }
                )
              Cesium.when(promise, (layer) => {
                if (layer) {
                  layer.clearMemoryImmediately = true
                  layer.residentRootTile = false
                  layer.isOverlapDisplayed = false
                  layer.orderIndependentTranslucency = true
                  layer.style3D &&
                    (layer.style3D.altitudeMode =
                      Cesium.HeightReference.CLAMP_TO_GROUND)
                  // 设置查询参数，用于BIM属性查询
                  if (passParams.dataService) {
                    if (
                      passParams.dataService.lastIndexOf(
                        '/datasets/'
                      ) !== -1
                    ) {
                      layer.setQueryParameter({
                        url: passParams.dataService.substring(
                          0,
                          passParams.dataService.lastIndexOf(
                            '/datasources/'
                          )
                        ),
                        dataSourceName:
                          passParams.dataService.lastIndexOf(
                            '/datasets/'
                          ) !== -1
                            ? passParams.dataService.substring(
                                passParams.dataService.lastIndexOf(
                                  '/datasources/'
                                ) + '/datasources/'.length,
                                passParams.dataService.lastIndexOf(
                                  '/datasets/'
                                )
                              )
                            : passParams.dataService.substring(
                                passParams.dataService.lastIndexOf(
                                  '/datasources/'
                                ) + '/datasources/'.length
                              ),
                        dataSetName:
                          passParams.dataService.substring(
                            passParams.dataService.lastIndexOf(
                              '/datasets/'
                            ) + '/datasets/'.length
                          ),
                        hasGeometry: false
                      })
                    } else {
                      layer.setQueryParameter({
                        url: passParams.dataService.substring(
                          0,
                          passParams.dataService.lastIndexOf(
                            '/datasources/'
                          )
                        ),
                        dataSourceName:
                          passParams.dataService.lastIndexOf(
                            '/datasets/'
                          ) !== -1
                            ? passParams.dataService.substring(
                                passParams.dataService.lastIndexOf(
                                  '/datasources/'
                                ) + '/datasources/'.length,
                                passParams.dataService.lastIndexOf(
                                  '/datasets/'
                                )
                              )
                            : passParams.dataService.substring(
                                passParams.dataService.lastIndexOf(
                                  '/datasources/'
                                ) + '/datasources/'.length
                              ),
                        hasGeometry: false
                      })
                    }
                  }
                  const find = this._layers.find(
                    (item) => item.id === passParams.id
                  )
                  if (find) {
                    find.name = [passParams.name]
                    find.layer = [layer]

                    this.fire('add', find)

                    New.$emit('showDataList', find)
                  }
                  resolve(true)
                } else {
                  console.error('添加失败')
                  resolve(false)
                }
              })
            } else if (
              serviceUrl.indexOf('/realspace/scenes/') ===
              -1
            ) {
              passParams.url = serviceUrl
              passParams.name = undefined
              if (
                passParams.dataList[
                  passParams.currentDataIndex
                ].resourceServiceDataInfoList.length
              ) {
                passParams.dataService =
                  passParams.dataList[
                    passParams.currentDataIndex
                  ].resourceServiceDataInfoList[0].serviceDataUrl
              } else {
                passParams.dataService = null
              }
              // this.addLayer(passParams)
              this.set({
                id: passParams.id,
                title: passParams.title,
                name: [],
                type: passParams.type,
                layer: [],
                from: passParams.from,
                serviceUrl: passParams.url,
                signService: passParams.signService,
                dataService: passParams.dataService,
                bimCode: passParams.bimCode,
                serviceType: '27',
                currentDataIndex:
                  passParams.currentDataIndex,
                dataList: passParams.dataList
              })

              promise = this._viewer.scene.open(
                passParams.url,
                passParams.name,
                {
                  autoSetView: false
                }
              )
              Cesium.when(promise, (layers) => {
                if (layers) {
                  // 设置查询参数，用于BIM属性查询
                  layers.forEach((layer) => {
                    // 每个子图层的透明度可能不一致，需要保存子图层的原始透明度，用于在图层工具中调整透明度时分别计算
                    if (layer.alpha !== undefined) {
                      layer.originAlpha = layer.alpha
                    } else if (layer.style3D) {
                      layer.originFillForeColorAlpha =
                        layer.style3D.fillForeColor.alpha
                    }
                    layer.clearMemoryImmediately = true
                    layer.residentRootTile = false
                    layer.isOverlapDisplayed = false
                    layer.orderIndependentTranslucency = true
                    layer.style3D &&
                      (layer.style3D.altitudeMode =
                        Cesium.HeightReference.CLAMP_TO_GROUND)
                    if (passParams.dataService) {
                      if (
                        passParams.dataService.lastIndexOf(
                          '/datasets/'
                        ) !== -1
                      ) {
                        layer.setQueryParameter({
                          url: passParams.dataService.substring(
                            0,
                            passParams.dataService.lastIndexOf(
                              '/datasources/'
                            )
                          ),
                          dataSourceName:
                            passParams.dataService.lastIndexOf(
                              '/datasets/'
                            ) !== -1
                              ? passParams.dataService.substring(
                                  passParams.dataService.lastIndexOf(
                                    '/datasources/'
                                  ) +
                                    '/datasources/'.length,
                                  passParams.dataService.lastIndexOf(
                                    '/datasets/'
                                  )
                                )
                              : passParams.dataService.substring(
                                  passParams.dataService.lastIndexOf(
                                    '/datasources/'
                                  ) + '/datasources/'.length
                                ),
                          dataSetName:
                            passParams.dataService.substring(
                              passParams.dataService.lastIndexOf(
                                '/datasets/'
                              ) + '/datasets/'.length
                            ),
                          hasGeometry: false
                        })
                      } else {
                        layer.setQueryParameter({
                          url: passParams.dataService.substring(
                            0,
                            passParams.dataService.lastIndexOf(
                              '/datasources/'
                            )
                          ),
                          dataSourceName:
                            passParams.dataService.lastIndexOf(
                              '/datasets/'
                            ) !== -1
                              ? passParams.dataService.substring(
                                  passParams.dataService.lastIndexOf(
                                    '/datasources/'
                                  ) +
                                    '/datasources/'.length,
                                  passParams.dataService.lastIndexOf(
                                    '/datasets/'
                                  )
                                )
                              : passParams.dataService.substring(
                                  passParams.dataService.lastIndexOf(
                                    '/datasources/'
                                  ) + '/datasources/'.length
                                ),
                          hasGeometry: false
                        })
                      }
                    }
                  })
                  const realName = layers.map(
                    (item) => item.name
                  )
                  const find = this._layers.find(
                    (item) => item.id === passParams.id
                  )
                  if (find) {
                    find.name = realName
                    find.layer = layers

                    this.fire('add', find)

                    New.$emit('showDataList', find)
                  }
                  resolve(true)
                } else {
                  console.error('添加失败')
                  resolve(false)
                }
              })
            } else {
              passParams.url = serviceUrl.substring(
                0,
                serviceUrl.indexOf('/scenes')
              )
              passParams.name = decodeURI(
                serviceUrl.substring(
                  serviceUrl.indexOf('/scenes/') +
                    '/scenes/'.length
                )
              )
              if (
                passParams.dataList[
                  passParams.currentDataIndex
                ].resourceServiceDataInfoList.length
              ) {
                passParams.dataService =
                  passParams.dataList[
                    passParams.currentDataIndex
                  ].resourceServiceDataInfoList[0].serviceDataUrl
              } else {
                passParams.dataService = null
              }
              // this.addLayer(passParams)
              this.set({
                id: passParams.id,
                title: passParams.title,
                name: [],
                type: passParams.type,
                layer: [],
                from: passParams.from,
                serviceUrl: passParams.url,
                signService: passParams.signService,
                dataService: passParams.dataService,
                bimCode: passParams.bimCode,
                serviceType: '27',
                currentDataIndex:
                  passParams.currentDataIndex,
                dataList: passParams.dataList
              })

              promise = this._viewer.scene.open(
                passParams.url,
                passParams.name,
                {
                  autoSetView: false
                }
              )
              Cesium.when(promise, (layers) => {
                if (layers) {
                  // 设置查询参数，用于BIM属性查询
                  layers.forEach((layer) => {
                    // 每个子图层的透明度可能不一致，需要保存子图层的原始透明度，用于在图层工具中调整透明度时分别计算
                    if (layer.alpha !== undefined) {
                      layer.originAlpha = layer.alpha
                    } else if (layer.style3D) {
                      layer.originFillForeColorAlpha =
                        layer.style3D.fillForeColor.alpha
                    }
                    layer.clearMemoryImmediately = true
                    layer.residentRootTile = false
                    layer.isOverlapDisplayed = false
                    layer.orderIndependentTranslucency = true
                    layer.style3D &&
                      (layer.style3D.altitudeMode =
                        Cesium.HeightReference.CLAMP_TO_GROUND)
                    if (passParams.dataService) {
                      if (
                        passParams.dataService.lastIndexOf(
                          '/datasets/'
                        ) !== -1
                      ) {
                        layer.setQueryParameter({
                          url: passParams.dataService.substring(
                            0,
                            passParams.dataService.lastIndexOf(
                              '/datasources/'
                            )
                          ),
                          dataSourceName:
                            passParams.dataService.lastIndexOf(
                              '/datasets/'
                            ) !== -1
                              ? passParams.dataService.substring(
                                  passParams.dataService.lastIndexOf(
                                    '/datasources/'
                                  ) +
                                    '/datasources/'.length,
                                  passParams.dataService.lastIndexOf(
                                    '/datasets/'
                                  )
                                )
                              : passParams.dataService.substring(
                                  passParams.dataService.lastIndexOf(
                                    '/datasources/'
                                  ) + '/datasources/'.length
                                ),
                          dataSetName:
                            passParams.dataService.substring(
                              passParams.dataService.lastIndexOf(
                                '/datasets/'
                              ) + '/datasets/'.length
                            ),
                          hasGeometry: false
                        })
                      } else {
                        layer.setQueryParameter({
                          url: passParams.dataService.substring(
                            0,
                            passParams.dataService.lastIndexOf(
                              '/datasources/'
                            )
                          ),
                          dataSourceName:
                            passParams.dataService.lastIndexOf(
                              '/datasets/'
                            ) !== -1
                              ? passParams.dataService.substring(
                                  passParams.dataService.lastIndexOf(
                                    '/datasources/'
                                  ) +
                                    '/datasources/'.length,
                                  passParams.dataService.lastIndexOf(
                                    '/datasets/'
                                  )
                                )
                              : passParams.dataService.substring(
                                  passParams.dataService.lastIndexOf(
                                    '/datasources/'
                                  ) + '/datasources/'.length
                                ),
                          hasGeometry: false
                        })
                      }
                    }
                  })
                  const realName = layers.map(
                    (item) => item.name
                  )
                  const find = this._layers.find(
                    (item) => item.id === passParams.id
                  )
                  if (find) {
                    find.name = realName
                    find.layer = layers

                    this.fire('add', find)

                    New.$emit('showDataList', find)
                  }
                  resolve(true)
                } else {
                  console.error('添加失败')
                  resolve(false)
                }
              })
            }
          }
          break
        default:
          resolve(false)
          break
      }
    })
  }

  del(id) {
    if (id === undefined) {
      // ;[...this._layers.values()].forEach((item) => {
      //   const { id, layer, type, name } = item
      //   // this._layers.delete(id)
      //   this._layers.splice(
      //     this._layers.findIndex((item) => item.id === id),
      //     1
      //   )
      //   this.fire('del', id)
      //   switch (type) {
      //     case 'geojson':
      //       this._viewer.dataSources.remove(layer)
      //       break
      //     case 'mvt':
      //       this._viewer.scene.removeVectorTilesMap(name)
      //       break
      //     case 'imagery':
      //       this._viewer.scene.imageryLayers.remove(layer)
      //       break
      //     case 'layer':
      //       name.forEach((nameItem, index) => {
      //         if (!nameItem) {
      //           // 没有name
      //           if (layer[index].imageryProvider) {
      //             // 是imagery
      //             this._viewer.scene.imageryLayers.remove(
      //               layer[index]
      //             )
      //           } else if (layer[index]._isTerrainZ) {
      //             // 是地形
      //             this._viewer.terrainProvider =
      //               new Cesium.EllipsoidTerrainProvider({})
      //           }
      //         } else {
      //           this._viewer.scene.layers.remove(nameItem)
      //         }
      //       })
      //       break
      //     case 'tileset':
      //       this._viewer.scene.primitives.remove(layer)
      //       break
      //     default:
      //       break
      //   }
      // })
      for (const item of this._layers) {
        const { id, layer, type, name } = item
        // this._layers.delete(id)
        // this._layers.splice(
        //   this._layers.findIndex((item) => item.id === id),
        //   1
        // )
        this.fire('del', id)
        switch (type) {
          case 'geojson':
            this._viewer.dataSources.remove(layer)
            break
          case 'mvt':
            this._viewer.scene.removeVectorTilesMap(name)
            break
          case 'imagery':
            // this._viewer.scene.imageryLayers.remove(layer)
            const find =
              this._viewer.scene.imageryLayers._layers.find(
                (temp) =>
                  temp.imageryProvider._baseUrl ===
                  layer.imageryProvider._baseUrl
              )
            if (find) {
              this._viewer.scene.imageryLayers.remove(find)
            }
            break
          case 'layer':
            name.forEach((nameItem, index) => {
              if (!nameItem) {
                // 没有name
                if (layer[index].imageryProvider) {
                  // 是imagery
                  this._viewer.scene.imageryLayers.remove(
                    layer[index]
                  )
                  const find =
                    this._viewer.scene.imageryLayers._layers.find(
                      (temp) =>
                        temp.imageryProvider._baseUrl ===
                        layer[index].imageryProvider
                          ._baseUrl
                    )
                  if (find) {
                    this._viewer.scene.imageryLayers.remove(
                      find
                    )
                  }
                } else if (layer[index]._isTerrainZ) {
                  // 是地形
                  this._viewer.terrainProvider =
                    new Cesium.EllipsoidTerrainProvider({})
                }
              } else {
                this._viewer.scene.layers.remove(nameItem)
              }
            })
            break
          case 'tileset':
            this._viewer.scene.primitives.remove(layer)
            break
          default:
            break
        }
      }
      this._layers = []
    } else {
      const { layer, type, name } = this.get(id)
      if (layer) {
        // this._layers.delete(id)
        this._layers.splice(
          this._layers.findIndex((item) => item.id === id),
          1
        )
        this.fire('del', id)
        switch (type) {
          case 'geojson':
            this._viewer.dataSources.remove(layer)
            break
          case 'mvt':
            this._viewer.scene.removeVectorTilesMap(name)
            break
          case 'imagery':
            // this._viewer.scene.imageryLayers.remove(layer)
            const find =
              this._viewer.scene.imageryLayers._layers.find(
                (temp) =>
                  temp.imageryProvider._baseUrl ===
                  layer.imageryProvider._baseUrl
              )
            if (find) {
              this._viewer.scene.imageryLayers.remove(find)
            }
            break
          case 'layer':
            name.forEach((nameItem, index) => {
              if (!nameItem) {
                // 没有name
                if (layer[index].imageryProvider) {
                  // 是imagery
                  // this._viewer.scene.imageryLayers.remove(
                  //   layer[index]
                  // )
                  const find =
                    this._viewer.scene.imageryLayers._layers.find(
                      (temp) =>
                        temp.imageryProvider._baseUrl ===
                        layer[index].imageryProvider
                          ._baseUrl
                    )
                  if (find) {
                    this._viewer.scene.imageryLayers.remove(
                      find
                    )
                  }
                } else if (layer[index]._isTerrainZ) {
                  // 是地形
                  this._viewer.terrainProvider =
                    new Cesium.EllipsoidTerrainProvider({})
                }
              } else {
                this._viewer.scene.layers.remove(nameItem)
              }
            })
            break
          case 'tileset':
            this._viewer.scene.primitives.remove(layer)
            break
          default:
            break
        }
      }
    }
  }

  set({
    id,
    title,
    name,
    layer,
    type,
    from,
    serviceUrl,
    signService,
    dataService,
    specialType,
    specialWord,
    bimCode,
    serviceType,
    currentDataIndex,
    dataList
  }) {
    // this._layers.set(id, {
    //   id,
    //   title,
    //   name,
    //   type,
    //   layer,
    //   from,
    //   serviceUrl,
    //   signService,
    //   dataService,
    //   specialType,
    //   specialWord,
    //   bimCode,
    //   serviceType,
    //   currentDataIndex,
    //   dataList
    // })
    this._layers.push({
      id,
      title,
      name,
      type,
      layer,
      from,
      serviceUrl,
      signService,
      dataService,
      specialType,
      specialWord,
      bimCode,
      serviceType,
      currentDataIndex,
      dataList
    })
    // this.fire('add', {
    //   id,
    //   title,
    //   name,
    //   type,
    //   layer,
    //   from,
    //   serviceUrl,
    //   signService,
    //   dataService,
    //   specialType,
    //   specialWord,
    //   bimCode,
    //   serviceType
    // })
  }

  get(id) {
    return this._layers.find((item) => item.id === id) || {}
  }

  addMvt({
    id,
    title,
    name,
    type,
    url,
    from,
    signService,
    dataService,
    serviceType,
    currentDataIndex,
    dataList,
    height = 0,
    visible = true,
    opacity = 1,
    autoFly = true,
    onLoad,
    onClick
  }) {
    this.set({
      id,
      title,
      name,
      type,
      layer: null,
      from,
      serviceUrl: url,
      signService: signService,
      dataService: dataService,
      serviceType,
      currentDataIndex,
      dataList
    })

    // 加载mvt
    const mvt = this._viewer.scene.addVectorTilesMap({
      url: url,
      // canvasWidth: 512,
      name: name,
      viewer: this._viewer
    })

    const find = this._layers.find((item) => item.id === id)
    if (find) {
      find.layer = mvt

      this.fire('add', find)

      New.$emit('showDataList', find)
    }

    if (
      url.indexOf(
        'map-mvt-B0106GongGongFuWuSheShi/restjsr/v1/vectortile/maps/B0106_%E5%85%AC%E5%85%B1%E6%9C%8D%E5%8A%A1%E8%AE%BE%E6%96%BD%E6%96%B0'
      ) !== -1
    ) {
      mvt.isOverlapDisplayed = true
    }
    // mvt.lineAntialiasing = true
    const mvpReadyPromise = mvt.readyPromise
    Cesium.when(mvpReadyPromise, (data) => {
      if (data) {
        // console.log('添加成功')
        // const bounds = mvt.rectangle
        // this._viewer.scene.camera.setView({
        //   destination: Cesium.Cartesian3.fromRadians(
        //     (bounds.east + bounds.west) * 0.5,
        //     (bounds.north + bounds.south) * 0.5,
        //     10000
        //   )
        // })
      } else {
        console.error('添加失败')
      }
    })
  }

  geoJson(url) {
    // 范围上传加载geojson 下一次上传将上一次上传范围清空
    this._viewer.dataSources.removeAll()
    if (url) {
      const geo = JSON.parse(url)
      const geojson = Cesium.GeoJsonDataSource.load(geo, {
        clampToGround: true
      })
      Cesium.when(geojson, (dataSource) => {
        if (dataSource) {
          this._viewer.dataSources.add(dataSource)
          this._viewer.flyTo(dataSource)
        }
      })
    }
  }

  addImagery({
    id,
    title,
    name,
    type,
    url,
    from,
    signService,
    dataService,
    specialType,
    specialWord,
    serviceType,
    currentDataIndex,
    dataList,
    height = 0,
    visible = true,
    opacity = 1,
    autoFly = true,
    onLoad,
    onClick
  }) {
    this.set({
      id,
      title,
      name,
      type,
      layer: null,
      from,
      serviceUrl: url,
      signService: signService,
      dataService: dataService,
      specialType: specialType,
      specialWord: specialWord,
      serviceType,
      currentDataIndex,
      dataList
    })

    const provider = new Cesium.SuperMapImageryProvider({
      url: url
    })
    const imagery =
      this._viewer.scene.imageryLayers.addImageryProvider(
        provider
      )

    const find = this._layers.find((item) => item.id === id)
    if (find) {
      find.layer = imagery

      this.fire('add', find)

      New.$emit('showDataList', find)
    }
    // this._viewer.zoomTo(imagery)
  }

  addLayer({
    id,
    title,
    name,
    type,
    url,
    from,
    signService,
    dataService,
    bimCode,
    serviceType,
    currentDataIndex,
    dataList,
    height = 0,
    visible = true,
    opacity = 1,
    autoFly = false,
    onLoad,
    onClick
  }) {
    this.set({
      id,
      title,
      name: [],
      type,
      layer: [],
      from,
      serviceUrl: url,
      signService: signService,
      dataService: dataService,
      bimCode: bimCode,
      serviceType: '27',
      currentDataIndex,
      dataList
    })

    const promise = this._viewer.scene.open(url, name, {
      autoSetView: autoFly
    })
    Cesium.when(promise, (layers) => {
      if (layers) {
        // this._viewer.flyTo(layer[0])
        // http://chengyu.caupdwest.com:7000/iserver/services/data-KeJiChengShuJuKu/rest/data/datasources/E_BIM数据库_子项一号楼
        // console.log('dataService', dataService)
        // console.log('数据服务地址', dataService.substring(0, dataService.lastIndexOf('/datasources/')))
        // console.log('数据源', dataService.substring(dataService.lastIndexOf('/datasources/') + '/datasources/'.length))

        // 设置查询参数，用于BIM属性查询
        layers.forEach((layer) => {
          // 每个子图层的透明度可能不一致，需要保存子图层的原始透明度，用于在图层工具中调整透明度时分别计算
          if (layer.alpha !== undefined) {
            layer.originAlpha = layer.alpha
          } else if (layer.style3D) {
            layer.originFillForeColorAlpha =
              layer.style3D.fillForeColor.alpha
          }

          layer.clearMemoryImmediately = true
          layer.residentRootTile = false
          layer.isOverlapDisplayed = false
          layer.orderIndependentTranslucency = true
          // layer.indexedDB &&
          //   (layer.indexedDBSetting.isGeoTilesRootNodeSave = true)
          layer.style3D &&
            (layer.style3D.altitudeMode =
              Cesium.HeightReference.CLAMP_TO_GROUND)
          if (dataService) {
            if (
              dataService.lastIndexOf('/datasets/') !== -1
            ) {
              layer.setQueryParameter({
                url: dataService.substring(
                  0,
                  dataService.lastIndexOf('/datasources/')
                ),
                dataSourceName:
                  dataService.lastIndexOf('/datasets/') !==
                  -1
                    ? dataService.substring(
                        dataService.lastIndexOf(
                          '/datasources/'
                        ) + '/datasources/'.length,
                        dataService.lastIndexOf(
                          '/datasets/'
                        )
                      )
                    : dataService.substring(
                        dataService.lastIndexOf(
                          '/datasources/'
                        ) + '/datasources/'.length
                      ),
                dataSetName: dataService.substring(
                  dataService.lastIndexOf('/datasets/') +
                    '/datasets/'.length
                ),
                hasGeometry: false
              })
              console.log(
                '设置查询参数',
                layer.getQueryParameter()
              )
            } else {
              layer.setQueryParameter({
                url: dataService.substring(
                  0,
                  dataService.lastIndexOf('/datasources/')
                ),
                dataSourceName:
                  dataService.lastIndexOf('/datasets/') !==
                  -1
                    ? dataService.substring(
                        dataService.lastIndexOf(
                          '/datasources/'
                        ) + '/datasources/'.length,
                        dataService.lastIndexOf(
                          '/datasets/'
                        )
                      )
                    : dataService.substring(
                        dataService.lastIndexOf(
                          '/datasources/'
                        ) + '/datasources/'.length
                      ),
                hasGeometry: false
              })
              console.log(
                '设置查询参数',
                layer.getQueryParameter()
              )
            }
          }
        })
        const realName = layers.map((item) => item.name)
        const find = this._layers.find(
          (item) => item.id === id
        )
        if (find) {
          find.name = realName
          find.layer = layers

          this.fire('add', find)

          New.$emit('showDataList', find)
        }
        // this.set({
        //   id,
        //   title,
        //   name: realName,
        //   type,
        //   // layer: this._viewer.scene.layers.find(name),
        //   layer: layers,
        //   from,
        //   serviceUrl: url,
        //   signService: signService,
        //   dataService: dataService,
        //   bimCode: bimCode,
        //   serviceType: '27'
        // })
      } else {
        console.error('添加失败')
      }
    })
  }

  addLayerByScp({
    id,
    title,
    name,
    type,
    url,
    from,
    signService,
    dataService,
    currentDataIndex,
    dataList,
    height = 0,
    visible = true,
    opacity = 1,
    autoFly = false,
    onLoad,
    onClick
  }) {
    this.set({
      id,
      title,
      name: [],
      type,
      layer: [],
      from,
      serviceUrl: url,
      signService: signService,
      dataService: dataService,
      serviceType: '27',
      currentDataIndex,
      dataList
    })
    const promise =
      this._viewer.scene.addS3MTilesLayerByScp(
        url + '/config',
        {
          autoSetView: autoFly,
          name: name
        }
      )
    Cesium.when(promise, (layer) => {
      if (layer) {
        layer.clearMemoryImmediately = true
        layer.residentRootTile = false
        layer.isOverlapDisplayed = false
        layer.orderIndependentTranslucency = true
        // layer.indexedDB &&
        //   (layer.indexedDBSetting.isGeoTilesRootNodeSave = true)
        layer.style3D &&
          (layer.style3D.altitudeMode =
            Cesium.HeightReference.CLAMP_TO_GROUND)
        this._viewer.flyTo(layer)
        // http://chengyu.caupdwest.com:7000/iserver/services/data-KeJiChengShuJuKu/rest/data/datasources/E_BIM数据库_子项一号楼
        // console.log('dataService', dataService)
        // console.log('数据服务地址', dataService.substring(0, dataService.lastIndexOf('/datasources/')))
        // console.log('数据源', dataService.substring(dataService.lastIndexOf('/datasources/') + '/datasources/'.length))

        // layer.indexedDBSetting.isGeoTilesRootNodeSave = true
        // 设置查询参数，用于BIM属性查询
        if (dataService) {
          if (
            dataService.lastIndexOf('/datasets/') !== -1
          ) {
            layer.setQueryParameter({
              url: dataService.substring(
                0,
                dataService.lastIndexOf('/datasources/')
              ),
              dataSourceName:
                dataService.lastIndexOf('/datasets/') !== -1
                  ? dataService.substring(
                      dataService.lastIndexOf(
                        '/datasources/'
                      ) + '/datasources/'.length,
                      dataService.lastIndexOf('/datasets/')
                    )
                  : dataService.substring(
                      dataService.lastIndexOf(
                        '/datasources/'
                      ) + '/datasources/'.length
                    ),
              dataSetName: dataService.substring(
                dataService.lastIndexOf('/datasets/') +
                  '/datasets/'.length
              ),
              hasGeometry: false
            })
            console.log(
              '设置查询参数',
              layer.getQueryParameter()
            )
          } else {
            layer.setQueryParameter({
              url: dataService.substring(
                0,
                dataService.lastIndexOf('/datasources/')
              ),
              dataSourceName:
                dataService.lastIndexOf('/datasets/') !== -1
                  ? dataService.substring(
                      dataService.lastIndexOf(
                        '/datasources/'
                      ) + '/datasources/'.length,
                      dataService.lastIndexOf('/datasets/')
                    )
                  : dataService.substring(
                      dataService.lastIndexOf(
                        '/datasources/'
                      ) + '/datasources/'.length
                    ),
              hasGeometry: false
            })
            console.log(
              '设置查询参数',
              layer.getQueryParameter()
            )
          }
        }
        const find = this._layers.find(
          (item) => item.id === id
        )
        if (find) {
          find.name = [name]
          find.layer = [layer]

          this.fire('add', find)

          New.$emit('showDataList', find)
        }
        // this.set({
        //   id,
        //   title,
        //   name: [name],
        //   type,
        //   // layer: this._viewer.scene.layers.find(name),
        //   layer: [layer],
        //   from,
        //   serviceUrl: url,
        //   signService: signService,
        //   dataService: dataService,
        //   serviceType: '27'
        // })
      } else {
        console.error('添加失败')
      }
    })
  }

  addGeojson({
    pkid,
    title,
    serviceName,
    serviceType,
    serviceUrl,
    from,
    height = 0,
    visible = true,
    opacity = 1,
    autoFly = true,
    onLoad,
    onClick
  }) {
    const geojson = Cesium.GeoJsonDataSource.load(
      serviceUrl,
      { clampToGround: true }
    )
    Cesium.when(geojson, (dataSource) => {
      if (dataSource) {
        this._viewer.dataSources.add(dataSource)
        // this._viewer.flyTo(dataSource)
        this.set({
          pkid,
          title,
          serviceName,
          serviceType,
          layer: dataSource,
          from
        })
      }
    })
  }

  addTileset({
    id,
    title,
    name,
    type,
    url,
    from,
    height = 0,
    visible = true,
    opacity = 1,
    autoFly = true,
    onLoad,
    onClick
  }) {
    const tileset = this._viewer.scene.primitives.add(
      new Cesium.Cesium3DTileset({
        url: url,
        isSuperMapiServer: false
      })
    )
    this._viewer.flyTo(tileset)
    this.set({
      id,
      title,
      name,
      type,
      layer: tileset,
      from
    })
  }
}
